<!--
 * @Author: xiaotiwen
 * @Date: 2020-05-18 11:19:03
 * @LastEditTime: 2020-07-21 16:10:24
 * @LastEditors: xiaotiwen
 * @FilePath: \eduweb\src\views\practiceManagement\practiceReworkManagement\reworkAdd.vue
 * @Description: 实践重修新增
 -->
<template>
    <div class="reworkAdd">
        <wordTable :data="data" :label="label" />
        <div class="reworkAdd_form">
            <el-form ref="form" :model="form" :rules="rules" label-width="180px">
                <el-form-item v-if="showStuFlag" :label="$t('practiceReworkManagement.label.applyForStudent')" prop="stuInfo" >
                    <!-- multiple -->
                    <el-select :disabled="!chooseFlag"
                        v-model="form.stuInfo"
                        :remote-method="selectStu"
                        @change="change($event)"
                        value-key="studentId"
                        :placeholder="$t('common.pla.pleaseSelect')"
                        filterable
                        remote
                        :clearable="true"
                        v-clearreadonly
                    >
                        <el-option
                            v-for="item in students"
                            :key="item.studentId"
                            :label="item.label"
                            :value="item.value"
                        />
                        </el-select>
                </el-form-item>
                <el-form-item
                    :label="$t('practiceReworkManagement.label.applyCourse')"
                    prop="courseName"
                >
                    <el-select
                        v-model="form.courseId"
                        :placeholder="$t('message.plzSelect')"
                        filterable
                    >
                        <el-option
                            v-for="(item) in options"
                            :key="item.courseId"
                            :label="item.courseName"
                            :value="item.courseId"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                    :label="$t('practiceReworkManagement.label.applyReason')"
                    prop="applyReason"
                >
                    <el-input
                        v-model="form.applyReason"
                        maxlength="200"
                        :rows="4"
                        type="textarea"
                        :placeholder="$t('fundingManagement.tips.plzInput')"
                        resize="none"
                    />
                </el-form-item>
                <el-form-item
                    v-if="!dialogType"
                    :label="$t('practiceReworkManagement.label.files')"
                >
                    <el-upload
                        :on-success="uploadDone"
                        :headers="{'X-Token': $store.state.session.sessionid}"
                        :data="{bucketname: 'face', folderpath: 'file'}"
                        :before-upload="beforeUpload"
                        :limit="1"
                        :on-exceed="handleExceed"
                        :on-remove="onRemove"
                        :file-list="fileList"
                        class="upload-demo"
                        action="/api/commonservice/obsfile/uploadfile"
                    >
                        <div class="reworkAdd_upload">
                            <el-button
                                size="small"
                                type="primary"
                            >{{$t('dispersionPracticeApply.btn.clickUpload')}}</el-button>
                            <div
                                class="reworkAdd_upload_div"
                            >{{$t('dispersionPracticeApply.tips.fileLimit')}}</div>
                        </div>
                    </el-upload>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import UTILS from 'common/src/utils/utils'
import wordTable from '../common/wordTable'
import { getDetail, getCourses } from 'common/src/api/practiceManagement/practiceReworkManagement'
import { getStuInfoByParam,findStuInfoListForSelect } from 'common/src/api/studentinfo'
import { findCampusProfessionList } from 'common/src/api/culture/campusProfession'
import mixin from 'common/src/mixins/index';
export default {
    // 组件名称
    name: 'ReworkAdd',
    mixins: [mixin],
    // 局部注册的组件
    components: {
        wordTable
    },
    // 组件参数 接收来自父组件的数据
    props: {
        ids: {
            type: String,
            default: ''
        },
        chooseFlag:{
            type: Boolean,
            default: false
        },
        showStuFlag:{
            type: Boolean,
            default: false
        }
    },
    // 组件状态值
    data() {
        return {
            fileList: [],
            form: {
                applyReason: '',
                // courseNames: {
                    courseName:'',
                    courseId: '',
                    renewalPayFlag: '',
                    collegeId: '',
                    collegeName:'',
                    credit:'',
                    courseNatureId:'',
                    courseLabelName:'',
                // },
                udgPtAttachTs: [],
                stuInfo:null
            },
            data: {}, // 数据类型
            label: [
                [
                    { label: this.$t('label.stuCode'), props: 'studentNo' },
                    { label: this.$t('label.stuName'), props: 'studentName' }
                ],
                [
                    { label: this.$t('label.college'), props: 'acdemyName' },
                    { label: this.$t('label.major'), props: 'majorName' }
                ],
                [{ label: this.$t('label.grade'), props: 'grade' }]
            ],
            options: [],
            rules: {
                stuInfo: [
                    {
                        required: true,
                        message: this.$t('practiceReworkManagement.tips.mustWrite'),
                        trigger: ['change']
                    }
                ],
                applyReason: [
                    {
                        required: true,
                        message: this.$t('practiceReworkManagement.tips.mustWrite'),
                        trigger: ['blur']
                    }
                ],
                courseName: [
                    { required: true, message: this.$t('message.plzSelect'), trigger: ['blur'] }
                ]
            },
            stuInfo:null,
            students:[]
        }
    },
    // 计算属性
    computed: {},
    // 侦听器
    watch: {},
    /**
     * 在实例初始化之后，组件属性计算之前，如data属性等
     */
    created() {},
    /**
     * 在挂载开始之前被调用：相关的 render 函数首次被调用。
     */
    mounted() {
        this.getDetails().then(res => {
            let jsonData = {
                studentNo: res,
                courseId: this.form.courseId,
                courseName: this.form.courseName,
                collegeId: this.form.collegeId,
                collegeName: this.form.collegeName
            }
            getCourses(jsonData).then(res1 => {
                if (res1 && res1.code !== 200) {
                    this.$message({ message: res.msg, type: 'warning' })
                    return
                }
                if(res1.data.length>0){
                    this.options = res1.data
                }
            })
        })
    },
    // 组件方法
    methods: {
        // courseNameCheck(rule, value, callback) {
        // if (!value.hasOwnProperty('courseId') || !value.courseId) {
        //     callback(new Error(this.$t('message.plzSelect')));
        // } else {
        //     callback()
        // }
        // return callback();
        // },
        getData(val) {
            let data = null
            this.$set(this.form, 'studentNo', this.data.studentNo)
            this.$set(this.form, 'studentName', this.data.studentName)
            this.$set(this.form, 'acdemyName', this.data.acdemyName)
            this.$set(this.form, 'grade', this.data.grade)
            this.$set(this.form, 'majorName', this.data.majorName)
            this.$set(this.form, 'acdemyId', this.data.acdemyId)
            this.$set(this.form, 'majorId', this.data.majorId)
            this.$set(this.form, 'courseDateStart', null)
            this.$set(this.form, 'courseDateEnd', null)
            if (this.ids) {
                this.$set(this.form, 'id', this.ids)
            }
            let courseId = this.form.courseId
            if (courseId) {
                let obj = this.options.find(v => v.courseId === courseId)
                this.$set(this.form, 'courseName', obj.courseName)
                this.$set(this.form, 'renewalPayFlag', obj.renewalPayFlag)
                this.$set(this.form, 'collegeId', obj.collegeId)
                this.$set(this.form, 'collegeName', obj.collegeName)
                this.$set(this.form, 'credit', obj.credit)
                this.$set(this.form, 'courseNatureId', obj.courseNatureId)
                this.$set(this.form, 'courseLabelName', obj.courseLabelName)
            }
            if (val === 'save') {
                data = this.form
            } else if (val === 'submit') {
                this.$refs.form.validate(valid => {
                    if (valid) {
                        data = this.form
                    }
                })
            }
            return data
        },
        handleExceed(files, fileList) {
            // 文件超出个数限制时的钩子
            this.$message.warning(
                UTILS.i18nReplace(this.$t('dispersionPracticeApply.tips.fileTips'), {
                    first: files.length,
                    second: files.length + fileList.length,
                    third: 1
                })
            )
        },
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.jpg,.png,.gif,.doc,.docx,.xls,.xlsx,.pdf',
                    size: '10'
                },
                this
            )
        },
        uploadDone(response, file) {
            let jsons = {
                attachName: file.name,
                attachSize: file.size,
                attachPath: Object.values(file.response.data)[0].objectkey
            }
            this.form.udgPtAttachTs = [jsons]
        },
        onRemove(file, fileList){
            this.form.udgPtAttachTs = []
        },
        getDetails() {
            return new Promise((resolve, reject) => {
                if (this.ids) {
                    //编辑
                    getDetail({ id: this.ids }).then(res => {
                        this.data = res.data
                        resolve(this.data.studentNo)
                        if (this.data.courseId) {
                            // let json = {
                            //     courseName: this.data.courseName,
                            //     courseId: this.data.courseId,
                            //     renewalPayFlag: this.data.renewalPayFlag
                            // }
                            this.form = this.data
                            // this.$set(this.form, 'courseNames', json)
                        } else {
                            for (const key in this.form) {
                                if (key !== 'courseNames') {
                                    this.form[key] = this.data[key]
                                }
                            }
                        }
                        if (this.data.udgPtAttachTs.length >= 1) {
                            this.fileList = [
                                {
                                    name: this.data.udgPtAttachTs[0].attachName,
                                    size: this.data.udgPtAttachTs[0].attachSize,
                                    url: this.data.udgPtAttachTs[0].attachPath
                                }
                            ]
                        }
                    })
                } else if(!this.showStuFlag){
                    //非管理员/教务员代新增
                        this.data = this.global.currentUser
                        resolve(this.data.uid)
                        this.$set(this.data, 'studentNo', this.data.uid);
                        this.$set(this.data, 'studentName', this.data.name);
                        this.$set(this.data, 'acdemyName', this.data.facultyName);
                        // 获取当前学生的年级专业
                        getStuInfoByParam(this.data.uid, encodeURIComponent('学籍信息')).then(res => {
                            // 获取年级
                            let grade
                            let major
                            res.data.forEach(function(value) {
                                if (value.columnStr === 'CULTURE_PROFESSION_') {
                                    major = value.value
                                }
                                if (value.columnStr === 'CURRENT_GRADE_') {
                                    grade = value.value
                                    //年级排序在专业之后，判断年级获取到即可
                                    return
                                }
                            })
                            this.data.grade = grade
                            // 通过年级专业code获取专业的名称
                            this.query(major, this.data.grade)
                        })

                }
            })
        },
        query(profession, grade) {
            // 专业代号查专业
            let lang = this.$store.getters.language || 'cn'
            let param = {}
            param.grade = grade
            param.keyWord = profession
            param.pageSize_ = 1
            param.pageNum_ = 1
            findCampusProfessionList(param).then(res => {
                let data = res.data.list
                if (data && data.length > 0) {
                    this.$set(this.data, 'acdemyId', data[0].faculty)
                    this.$set(this.data, 'majorId', data[0].professionCode)
                    if (lang === 'cn') {
                        this.$set(this.data, 'majorName', data[0].professionName)
                    } else {
                        this.$set(this.data, 'majorName', data[0].professionNameEn)
                    }
                }
            })
        },
        change(item){
            if (!item || !item.studentId) return;
            if(item){
                this.$set(this.data, 'studentNo', item.studentId);
                this.$set(this.data, 'studentName', item.name);
                this.$set(this.data, 'acdemyName', item.facultyI18n);
                this.$set(this.data, 'acdemyId', item.faculty)
                this.$set(this.data, 'majorId', item.cultureProfession)
                this.$set(this.data, 'grade', item.grade)
                this.$set(this.data, 'majorName', item.cultureProfessionI18n)
            }
            let jsonData = {
                studentNo: item.studentId
            }
            getCourses(jsonData).then(res1 => {
                if (res1 && res1.code !== 200) {
                    this.$message({ message: res.msg, type: 'warning' })
                    return
                }
                if(res1.data.length>0){
                    this.options = res1.data
                }
            })
        },
        transStudentData(list, name, code) {
            return list.map((item, index, array) => {
                return {
                    label: item[name] + '(' + item[code] + ')',
                    value: item,
                }
             })
        },
        // 查询学生信息接口
        selectStu (query) {
            if (!query) return;
            const data = {
                name: query,
                pageNum_: 1,
                pageSize_: 50
            }
            this.loading = true
            findStuInfoListForSelect(data).then(res => {
                this.loading = false
                if (res.code == 200) {
                    this.students = this.transStudentData(res.data.list, 'name', 'studentId')
                    // this.students = res.data.list
                } else throw res.code
            })
            .catch(error => {
              this.loading = false
              this.$message({
                  type: 'error',
                  message: '查询用户出错'
              })
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.reworkAdd {
    &_form {
        padding-top: 20px;
    }
    &_upload {
        display: flex;
        align-items: center;
        &_div {
            margin-left: 10px;
        }
    }
    ::v-deep .el-upload-list__item {
        width: 220px;
    }
}
</style>
